
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using Apps.Models;
using Apps.Common;
using Microsoft.Practices.Unity;
using System.Transactions;
using Apps.BLL.Core;
using Apps.Locale;
using LinqToExcel;
using System.IO;
using System.Text;
using System.Linq.Expressions;
using Apps.IDAL.PUB;
using Apps.IBLL.PUB;
namespace Apps.BLL.PUB
{
    public class PUB_SCHEMEBLL: IPUB_SCHEMEBLL
    {
        [Dependency]
        public IPUB_SCHEMERepository m_Rep { get; set; }
        public DBContainer db = new DBContainer();

        public virtual List<PUB_SCHEMEModel> GetList(ref GridPager pager, string queryStr)
        {

            IQueryable<PUB_SCHEME> queryData = null;
            if (!string.IsNullOrWhiteSpace(queryStr))
            {
                queryData = m_Rep.GetList(
                                a => a.SCHEME_ID.Contains(queryStr)
                                //|| a.SCHEME_TYPE.Contains(queryStr)
                                || a.SCHEME_MARK.Contains(queryStr)
                                || a.COMPILE_USER.Contains(queryStr)
                                );
            }
            else
            {
                queryData = m_Rep.GetList();
            }
            pager.totalRows = queryData.Count();
            //排序
            queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
            return CreateModelList(ref queryData);
        }
        public List<PUB_SCHEMEModel> GetList(ref GridPager pager, string EFFECTIVE_DATES, string EFFECTIVE_DATEE, string SCHEME_TYPE, string LAYOUT_TYPE, string COMPILE_USER)
        {
            IQueryable<PUB_SCHEME> queryData = null;
            if (!string.IsNullOrWhiteSpace(EFFECTIVE_DATES))
            {
                DateTime FDATETime = Convert.ToDateTime(EFFECTIVE_DATES);
                queryData = queryData.Where(m => m.EFFECTIVE_DATE >= FDATETime);
            }
            if (!string.IsNullOrWhiteSpace(EFFECTIVE_DATEE))
            {
                DateTime FDATETime = Convert.ToDateTime(EFFECTIVE_DATEE);
                queryData = queryData.Where(m => m.EFFECTIVE_DATE <= FDATETime);
            }
            if (!string.IsNullOrWhiteSpace(SCHEME_TYPE) && SCHEME_TYPE != "-1")
            {
                queryData = queryData.Where(m => m.SCHEME_TYPE == SCHEME_TYPE);
            }
            if (!string.IsNullOrWhiteSpace(LAYOUT_TYPE) && LAYOUT_TYPE != "-1")
            {
                int LAYOUT_TYPE2 = Convert.ToInt32(LAYOUT_TYPE);
                queryData = queryData.Where(m => m.LAYOUT_TYPE == LAYOUT_TYPE2);
            }
            if (!string.IsNullOrWhiteSpace(COMPILE_USER) && COMPILE_USER != "-1")
            {
                queryData = queryData.Where(m => m.COMPILE_USER == COMPILE_USER);
            }

            var data = from m1 in queryData
                       join m3 in db.SysUser on m1.SCHEME_ID equals m3.Id into l3
                       from l33 in l3.DefaultIfEmpty()

                       select new PUB_SCHEMEModel()
                       {
                           SCHEME_ID = m1.SCHEME_ID,
                           EFFECTIVE_DATE = m1.EFFECTIVE_DATE,
                           SCHEME_TYPE = m1.SCHEME_TYPE,
                           LAYOUT_TYPE = m1.LAYOUT_TYPE,
                           CAR_COUNT = m1.CAR_COUNT,
                           COAL_TOTAL = m1.COAL_TOTAL,
                           POINT_SUM = m1.POINT_SUM,
                           POINT_COUNT = m1.POINT_COUNT,
                           SCHEME_MARK = m1.SCHEME_MARK,
                           STATUS = m1.STATUS,
                           COMPILE_USER = m1.COMPILE_USER,
                           COMPILE_DATE = m1.COMPILE_DATE,
                           SAMPLE_MACHINE_GROUP=m1.SAMPLE_MACHINE_GROUP,
                           // COMPILE_USERName = m1.TrueName,
                           // BATCH_CODE = model.PL_RC_DETAILS.Count > 0 ? model.PL_RC_DETAILS.FirstOrDefault().BATCH_CODE : ""
                       };


            pager.totalRows = data.Count();
            //排序
            data = LinqHelper.SortingAndPaging(data, pager.sort, pager.order, pager.page, pager.rows);
            var retval = data.ToList();
            return retval;
        }
        public virtual List<V_PUB_SCHEMEModel> GetPagerList(ref GridPager pager, Expression<Func<V_PUB_SCHEME, bool>> whereLambda)
        {
            try
            {

                var queryData = m_Rep.Context.V_PUB_SCHEME.Where(whereLambda.Compile());
                var queryData2 = from model in queryData
                                     //join p1 in m_Rep.Context.SysUser on model.COMPILE_USER equals p1.UserName into jd1
                                     //from ud in jd1.DefaultIfEmpty()
                                 select new V_PUB_SCHEMEModel
                                 {
                                     SCHEME_ID = model.SCHEME_ID,
                                     EFFECTIVE_DATE = model.EFFECTIVE_DATE,
                                     SCHEME_TYPE = model.SCHEME_TYPE,
                                     SCHEME_TYPE_STR = model.SCHEME_TYPE_STR,
                                     LAYOUT_TYPE = model.LAYOUT_TYPE,
                                     CAR_COUNT = model.CAR_COUNT,
                                     COAL_TOTAL = model.COAL_TOTAL,
                                     POINT_SUM = model.POINT_SUM,
                                     POINT_COUNT = model.POINT_COUNT,
                                     SCHEME_MARK = model.SCHEME_MARK,
                                     STATUS = model.STATUS,
                                     COMPILE_USER = model.COMPILE_USER,
                                     USERNAME = model.USERNAME,
                                     COMPILE_DATE = model.COMPILE_DATE,
                                     //COMPILE_USERName = ud.TrueName,
                                     SAMPLE_MACHINE_GROUP = model.SAMPLE_MACHINE_GROUP,
                                     SAMPLE_MACHINE_GROUP_STR = model.SAMPLE_MACHINE_GROUP_STR,
                                     BATCH_CODE = model.BATCH_CODE
                                     //BATCH_CODE = model.PL_RC_DETAILS.Count > 0 ? model.PL_RC_DETAILS.FirstOrDefault().BATCH_CODE : ""
                                 };

                pager.totalRows = queryData2.Count();
                //排序
                return LinqHelper.SortingAndPaging(queryData2.AsQueryable(), pager.sort, pager.order, pager.page, pager.rows).ToList();
            }
            catch (Exception ex)
            {

                throw ex;
            }
           // IQueryable<PUB_SCHEME> queryData = this.db.PUB_SCHEME.AsQueryable<PUB_SCHEME>();


        }

        public virtual List<PUB_SCHEMEModel> GetPagerListByComb(ref GridPager pager, Expression<Func<PUB_SCHEME, bool>> whereLambda)
        {

            IQueryable<PUB_SCHEME> queryData = m_Rep.GetList();

            queryData = queryData.Where(whereLambda.Compile()).AsQueryable();

            pager.totalRows = queryData.Count();
            //排序
            queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
            return CreateModelList(ref queryData);
        }

        public virtual List<PUB_SCHEMEModel> GetList(Expression<Func<PUB_SCHEME, bool>> whereLambda)
        {

            IQueryable<PUB_SCHEME> queryData = m_Rep.GetList(whereLambda);

            return CreateModelList(ref queryData);
        }

        public virtual List<PUB_SCHEMEModel> GetListByComb(Expression<Func<PUB_SCHEME, bool>> whereLambda)
        {

            IQueryable<PUB_SCHEME> queryData = m_Rep.GetList();

            queryData = queryData.Where(whereLambda.Compile()).AsQueryable();

            return CreateModelList(ref queryData);
        }

        public virtual List<PUB_SCHEMEModel> GetListByParentId(ref GridPager pager, string queryStr, object parentId)
        {
            return new List<PUB_SCHEMEModel>();
        }

        public virtual List<PUB_SCHEMEModel> CreateModelList(ref IQueryable<PUB_SCHEME> queryData)
        {

            List<PUB_SCHEMEModel> modelList = (from r in queryData
                                               select new PUB_SCHEMEModel
                                               {
                                                   SCHEME_ID = r.SCHEME_ID,
                                                   EFFECTIVE_DATE = r.EFFECTIVE_DATE,
                                                   BATCH_CODE =r.PL_RC_DETAILS.FirstOrDefault().BATCH_CODE,
                                                   SCHEME_TYPE = r.SCHEME_TYPE,
                                                   LAYOUT_TYPE = r.LAYOUT_TYPE,
                                                   CAR_COUNT = r.CAR_COUNT,
                                                   COAL_TOTAL = r.COAL_TOTAL,
                                                   POINT_SUM = r.POINT_SUM,
                                                   POINT_COUNT = r.POINT_COUNT,
                                                   SCHEME_MARK = r.SCHEME_MARK,
                                                   STATUS = r.STATUS,
                                                   COMPILE_USER = r.COMPILE_USER,
                                                   COMPILE_DATE = r.COMPILE_DATE,
                                                   COMPILE_USERName=r.COMPILE_USER,
                                                   SAMPLE_MACHINE_GROUP=r.SAMPLE_MACHINE_GROUP,

                                               }).ToList();

            return modelList;
        }

        public virtual bool Create(ref ValidationErrors errors, PUB_SCHEMEModel model)
        {
            try
            {
                //if (DateTime.Now.Date > model.EFFECTIVE_DATE.GetDateTime().Date)
                //{
                //    errors.Add("已生效的入厂采样方案不能修改！");
                //    return false;
                //}
                
                V_PUB_SCHEME ventity = m_Rep.Context.V_PUB_SCHEME.Where(m => m.SCHEME_ID == model.SCHEME_ID).FirstOrDefault();
                if (ventity != null)
                {
                    errors.Add(Resource.PrimaryRepeat);
                    return false;
                }
                if (model.STATUS == 1)
                {
                    //是否存在同批次的采样方案（存在则修改采样方案状态后创建新的采样方案，不存在则直接创建新的采样方案）
                    List<V_PUB_SCHEME> list = m_Rep.Context.V_PUB_SCHEME.Where(m => m.BATCH_CODE == model.PLANNAME && m.STATUS == 1).ToList();

                    if (list.Count() > 0)
                    {
                        for (int i = 0; i < list.Count(); i++)
                        {
                            PUB_SCHEME item = new PUB_SCHEME();
                            item.SCHEME_ID = list[i].SCHEME_ID;
                            item.STATUS = 2;//设为废弃

                            m_Rep.Context.Set<PUB_SCHEME>().Attach(item);
                            //标识 实体对象 某些属性 已经被修改了
                            m_Rep.Context.Entry<PUB_SCHEME>(item).Property("STATUS").IsModified = true;

                            db.Configuration.ValidateOnSaveEnabled = false;
                        }
                    }
                }
                PUB_SCHEME entity = new PUB_SCHEME();
                entity.SCHEME_ID = model.SCHEME_ID;
                entity.EFFECTIVE_DATE = model.EFFECTIVE_DATE;
                entity.SCHEME_TYPE = model.SCHEME_TYPE;
                entity.LAYOUT_TYPE = model.LAYOUT_TYPE;
                entity.CAR_COUNT = model.CAR_COUNT;
                entity.COAL_TOTAL = model.COAL_TOTAL;
                entity.POINT_SUM = model.POINT_SUM;
                entity.POINT_COUNT = model.POINT_COUNT;
                entity.SCHEME_MARK = model.SCHEME_MARK;
                entity.STATUS = model.STATUS;
                entity.COMPILE_USER = model.COMPILE_USER;
                entity.COMPILE_DATE = model.COMPILE_DATE;
                entity.SAMPLE_MACHINE_GROUP = model.SAMPLE_MACHINE_GROUP;
                entity.SAMPLE_MACHINE = model.SAMPLE_MACHINE;

                if (string.IsNullOrEmpty(model.PLANID))
                {
                    if (m_Rep.Context.PUB_SCHEME.Where(m => m.EFFECTIVE_DATE == model.EFFECTIVE_DATE && m.RC_SCHEME_PLAN.Count == 0).Count() > 0)
                    {
                        errors.Add("已存在相同生效日期的入厂采样方案");
                        return false;
                    }
                    entity.RC_SCHEME_PLAN = null;
                }
                else
                {
                    RC_SCHEME_PLAN rcitem = new RC_SCHEME_PLAN();
                    rcitem.DETAIL_ID = model.PLANID;
                    rcitem.SCHEME_ID = model.SCHEME_ID;
                    entity.RC_SCHEME_PLAN.Add(rcitem);
                }

                m_Rep.Context.PUB_SCHEME.Add(entity);
                
                if (m_Rep.Context.SaveChanges() > 0)
                {
                    return true;
                }
                else
                {
                    errors.Add(Resource.InsertFail);
                    return false;
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public virtual bool Deletes(ref ValidationErrors errors, Expression<Func<PUB_SCHEME, bool>> whereLambda)
        {
            try
            {
                using (DBContainer db = new DBContainer())
                {

                    foreach (var entity in db.PUB_SCHEME.Where(whereLambda))
                    {
                        db.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
                    }

                    if (db.SaveChanges() > 0)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }

                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public virtual bool Delete(ref ValidationErrors errors, object id)
        {
            try
            {
                string SCHEME_ID = id.ToString();
                var mPUB_SCHEME = m_Rep.Context.PUB_SCHEME.Include("PL_RC_DETAILS").Single(m => m.SCHEME_ID == SCHEME_ID);
                m_Rep.Context.PUB_SCHEME.Remove(mPUB_SCHEME);
                return m_Rep.Context.SaveChanges() > 0;
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public virtual bool Delete(ref ValidationErrors errors, object[] deleteCollection)
        {
            try
            {
                if (deleteCollection != null)
                {
                    using (TransactionScope transactionScope = new TransactionScope())
                    {
                        if (m_Rep.Delete(deleteCollection) == deleteCollection.Length)
                        {
                            transactionScope.Complete();
                            return true;
                        }
                        else
                        {
                            Transaction.Current.Rollback();
                            return false;
                        }
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public virtual bool Edit(ref ValidationErrors errors, PUB_SCHEMEModel model)
        {
            try
            {
                #region 数据约束

                if (model.SCHEME_TYPE == "0")
                {
                    if (model.CAR_COUNT == null)
                    {
                        errors.Add("预计车数不能为空！");
                        return false;
                    }
                }
                if (model.SCHEME_TYPE == "1")
                {
                    if (model.COAL_TOTAL == null)
                    {
                        errors.Add("预计来煤量不能为空！");
                        return false;
                    }
                }

                if (model.CAR_COUNT < 0)
                {
                    errors.Add("预计车数必须大于等于0！");
                    return false;
                }

                if (model.COAL_TOTAL < 0)
                {
                    errors.Add("预计来煤量必须大于等于0！");
                    return false;
                }

                if (model.POINT_SUM < 0)
                {
                    errors.Add("总采样点数必须大于等于0！");
                    return false;
                }

                if (model.POINT_COUNT < 0)
                {
                    errors.Add("每车采样点数必须大于等于0！");
                    return false;
                }

                if (string.IsNullOrEmpty(model.SCHEME_MARK))
                {
                    errors.Add("方案说明不能为空！");
                    return false;
                }

                if (string.IsNullOrEmpty(model.SCHEME_MARK))
                {
                    errors.Add("方案说明不能为空！");
                    return false;
                }

                if (DateTime.Now.Date > model.EFFECTIVE_DATE.GetDateTime().Date)
                {
                    errors.Add("已过期的入厂采样方案不能修改！");
                    return false;
                }
                #endregion


                var entity = m_Rep.Context.PUB_SCHEME.SingleOrDefault(m => m.SCHEME_ID == model.SCHEME_ID);
                if (entity == null)
                {
                    errors.Add(Resource.Disable);
                    return false;
                }
                if (entity.COMPILE_USER != model.COMPILE_USER)
                {
                    errors.Add("只能编写人修改");
                    return false;
                }
                if (entity.STATUS == 1)
                {
                    errors.Add("已启用的采样方案不能进行删改操作");
                    return false;
                }
                if (model.STATUS == 1)
                {
                    //是否存在同批次的采样方案（存在则修改采样方案状态后编辑采样方案，不存在则直接编辑采样方案）
                    List<V_PUB_SCHEME> list = m_Rep.Context.V_PUB_SCHEME.Where(m => m.BATCH_CODE == model.PLANNAME && m.STATUS == 1).ToList();

                    if (list.Count() > 0)
                    {
                        for (int i = 0; i < list.Count(); i++)
                        {
                            PUB_SCHEME item = new PUB_SCHEME();
                            item.SCHEME_ID = list[i].SCHEME_ID;
                            item.STATUS = 2;//设为废弃

                            m_Rep.Context.Set<PUB_SCHEME>().Attach(item);
                            //标识 实体对象 某些属性 已经被修改了
                            m_Rep.Context.Entry<PUB_SCHEME>(item).Property("STATUS").IsModified = true;

                            db.Configuration.ValidateOnSaveEnabled = false;
                        }
                    }
                }
                entity.SCHEME_ID = model.SCHEME_ID;
                entity.EFFECTIVE_DATE = model.EFFECTIVE_DATE;
                entity.SCHEME_TYPE = model.SCHEME_TYPE;
                entity.LAYOUT_TYPE = model.LAYOUT_TYPE;
                entity.CAR_COUNT = model.CAR_COUNT;
                entity.COAL_TOTAL = model.COAL_TOTAL;
                entity.POINT_SUM = model.POINT_SUM;
                entity.POINT_COUNT = model.POINT_COUNT;
                entity.SCHEME_MARK = model.SCHEME_MARK;
                entity.STATUS = model.STATUS;
                entity.SAMPLE_MACHINE_GROUP = model.SAMPLE_MACHINE_GROUP;
                entity.SAMPLE_MACHINE = model.SAMPLE_MACHINE;
                entity.COMPILE_USER = model.COMPILE_USER;
                entity.COMPILE_DATE = model.COMPILE_DATE;
                if (string.IsNullOrEmpty(model.PLANID))
                {
                    if (m_Rep.Context.PUB_SCHEME.Where(m => m.EFFECTIVE_DATE == model.EFFECTIVE_DATE && m.SCHEME_ID != model.SCHEME_ID && m.RC_SCHEME_PLAN.Count == 0).Count() > 0)
                    {
                        errors.Add("已存在相同生效日期的入厂采样方案");
                        return false;
                    }
                    entity.RC_SCHEME_PLAN =null;
                }
                else
                {
                    RC_SCHEME_PLAN scheme = new RC_SCHEME_PLAN() { SCHEME_ID = model.SCHEME_ID };

                    m_Rep.Context.Entry<RC_SCHEME_PLAN>(scheme).State = System.Data.Entity.EntityState.Deleted;

                    RC_SCHEME_PLAN rcitem = new RC_SCHEME_PLAN();
                    rcitem.DETAIL_ID = model.PLANID;
                    rcitem.SCHEME_ID = model.SCHEME_ID;
                    entity.RC_SCHEME_PLAN.Add(rcitem);
                }


                if (m_Rep.Context.SaveChanges() > 0)
                {
                    return true;
                }
                else
                {
                    errors.Add(Resource.NoDataChange);
                    return false;
                }

            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public virtual PUB_SCHEMEModel GetById(object id)
        {
            string SCHEME_ID = id.ToString();
            if (IsExists(id))
            {
                try
                {
                    var entity = (from model in m_Rep.Context.V_PUB_SCHEME
                                  where model.SCHEME_ID == SCHEME_ID
                                  select new PUB_SCHEMEModel
                                  {
                                      SCHEME_ID = model.SCHEME_ID,
                                      EFFECTIVE_DATE = model.EFFECTIVE_DATE,
                                      SCHEME_TYPE = model.SCHEME_TYPE,
                                      LAYOUT_TYPE = model.LAYOUT_TYPE,
                                      CAR_COUNT = model.CAR_COUNT,
                                      COAL_TOTAL = model.COAL_TOTAL,
                                      POINT_SUM = model.POINT_SUM,
                                      POINT_COUNT = model.POINT_COUNT,
                                      SCHEME_MARK = model.SCHEME_MARK,
                                      STATUS = model.STATUS,
                                      COMPILE_USER = model.COMPILE_USER,
                                      COMPILE_DATE = model.COMPILE_DATE,
                                      COMPILE_USERName = model.USERNAME,
                                      SAMPLE_MACHINE_GROUP = model.SAMPLE_MACHINE_GROUP,
                                      SAMPLE_MACHINE = model.SAMPLE_MACHINE_GROUP_STR,
                                      //PLANID = model.PL_RC_DETAILS.FirstOrDefault().DETAIL_ID,
                                      //MATERIEL_NAME = model.PL_RC_DETAILS.FirstOrDefault().PUB_MATERIEL.MATERIEL_NAME,
                                      //PLAN_DATE = model.PL_RC_DETAILS.FirstOrDefault().PLAN_DATE,
                                      BATCH_CODE = model.BATCH_CODE
                                  }).FirstOrDefault();
                return entity;
                }
                catch (Exception ex)
                {
                    //errors.Add(ex.Message);
                    ExceptionHander.WriteException(ex);
                    return null;
                }
            }
            else
            {
                return null;
            }
        }

        public virtual PUB_SCHEMEModel GetItem(Expression<Func<PUB_SCHEME, bool>> whereLambda)
        {

            PUB_SCHEME entity = m_Rep.GetItem(whereLambda);
            if (entity == null) return null;

            PUB_SCHEMEModel model = new PUB_SCHEMEModel();
            model.SCHEME_ID = entity.SCHEME_ID;
            model.EFFECTIVE_DATE = entity.EFFECTIVE_DATE;
            model.SCHEME_TYPE = entity.SCHEME_TYPE;
            model.LAYOUT_TYPE = entity.LAYOUT_TYPE;
            model.CAR_COUNT = entity.CAR_COUNT;
            model.COAL_TOTAL = entity.COAL_TOTAL;
            model.POINT_SUM = entity.POINT_SUM;
            model.POINT_COUNT = entity.POINT_COUNT;
            model.SCHEME_MARK = entity.SCHEME_MARK;
            model.STATUS = entity.STATUS;
            model.COMPILE_USER = entity.COMPILE_USER;
            model.COMPILE_DATE = entity.COMPILE_DATE;
            model.SAMPLE_MACHINE_GROUP = entity.SAMPLE_MACHINE_GROUP;
            return model;
        }

        /// <summary>
        /// 校验Excel数据,这个方法一般用于重写校验逻辑
        /// </summary>
        public virtual bool CheckImportData(string fileName, List<PUB_SCHEMEModel> list, ref ValidationErrors errors)
        {

            var targetFile = new FileInfo(fileName);

            if (!targetFile.Exists)
            {

                errors.Add("导入的数据文件不存在");
                return false;
            }

            var excelFile = new ExcelQueryFactory(fileName);

            //对应列头
            excelFile.AddMapping<PUB_SCHEMEModel>(x => x.SCHEME_ID, "SCHEME_ID");
            excelFile.AddMapping<PUB_SCHEMEModel>(x => x.EFFECTIVE_DATE, "EFFECTIVE_DATE");
            excelFile.AddMapping<PUB_SCHEMEModel>(x => x.SCHEME_TYPE, "SCHEME_TYPE");
            excelFile.AddMapping<PUB_SCHEMEModel>(x => x.LAYOUT_TYPE, "LAYOUT_TYPE");
            excelFile.AddMapping<PUB_SCHEMEModel>(x => x.CAR_COUNT, "CAR_COUNT");
            excelFile.AddMapping<PUB_SCHEMEModel>(x => x.COAL_TOTAL, "COAL_TOTAL");
            excelFile.AddMapping<PUB_SCHEMEModel>(x => x.POINT_SUM, "POINT_SUM");
            excelFile.AddMapping<PUB_SCHEMEModel>(x => x.POINT_COUNT, "POINT_COUNT");
            excelFile.AddMapping<PUB_SCHEMEModel>(x => x.SCHEME_MARK, "SCHEME_MARK");
            excelFile.AddMapping<PUB_SCHEMEModel>(x => x.STATUS, "STATUS");
            excelFile.AddMapping<PUB_SCHEMEModel>(x => x.COMPILE_USER, "COMPILE_USER");
            excelFile.AddMapping<PUB_SCHEMEModel>(x => x.COMPILE_DATE, "COMPILE_DATE");

            //SheetName
            var excelContent = excelFile.Worksheet<PUB_SCHEMEModel>(0);
            int rowIndex = 1;
            //检查数据正确性
            foreach (var row in excelContent)
            {
                var errorMessage = new StringBuilder();
                var entity = new PUB_SCHEMEModel();
                entity.SCHEME_ID = row.SCHEME_ID;
                entity.EFFECTIVE_DATE = row.EFFECTIVE_DATE;
                entity.SCHEME_TYPE = row.SCHEME_TYPE;
                entity.LAYOUT_TYPE = row.LAYOUT_TYPE;
                entity.CAR_COUNT = row.CAR_COUNT;
                entity.COAL_TOTAL = row.COAL_TOTAL;
                entity.POINT_SUM = row.POINT_SUM;
                entity.POINT_COUNT = row.POINT_COUNT;
                entity.SCHEME_MARK = row.SCHEME_MARK;
                entity.STATUS = row.STATUS;
                entity.COMPILE_USER = row.COMPILE_USER;
                entity.COMPILE_DATE = row.COMPILE_DATE;

                //=============================================================================
                if (errorMessage.Length > 0)
                {
                    errors.Add(string.Format(
                        "第 {0} 列发现错误：{1}{2}",
                        rowIndex,
                        errorMessage,
                        "<br/>"));
                }
                list.Add(entity);
                rowIndex += 1;
            }
            if (errors.Count > 0)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        public virtual void SaveImportData(IEnumerable<PUB_SCHEMEModel> list)
        {
            try
            {
                using (DBContainer db = new DBContainer())
                {
                    foreach (var model in list)
                    {
                        PUB_SCHEME entity = new PUB_SCHEME();
                        entity.SCHEME_ID = model.SCHEME_ID;
                        entity.EFFECTIVE_DATE = model.EFFECTIVE_DATE;
                        entity.SCHEME_TYPE = model.SCHEME_TYPE;
                        entity.LAYOUT_TYPE = model.LAYOUT_TYPE;
                        entity.CAR_COUNT = model.CAR_COUNT;
                        entity.COAL_TOTAL = model.COAL_TOTAL;
                        entity.POINT_SUM = model.POINT_SUM;
                        entity.POINT_COUNT = model.POINT_COUNT;
                        entity.SCHEME_MARK = model.SCHEME_MARK;
                        entity.STATUS = model.STATUS;
                        entity.COMPILE_USER = model.COMPILE_USER;
                        entity.COMPILE_DATE = model.COMPILE_DATE;
                        entity.SAMPLE_MACHINE_GROUP = model.SAMPLE_MACHINE_GROUP;

                        db.PUB_SCHEME.Add(entity);
                    }
                    db.SaveChanges();
                }
            }
            catch
            {
                throw;
            }
        }


        public virtual bool IsExists(object id)
        {
            return m_Rep.IsExist(id);
        }

        public void Dispose()
        {

        }

        public bool Enable(ref ValidationErrors errors, string SCHEME_ID, string OldSTATUS)
        {
            try
            {
                int intSTATUS = 0;

             
                if (string.IsNullOrEmpty(OldSTATUS))
                {
                    errors.Add("状态不正确");
                    return false;
                }
                else
                {
                    intSTATUS = Convert.ToInt16(OldSTATUS);
                }
                PUB_SCHEME entity = m_Rep.Context.PUB_SCHEME.Where(m => m.SCHEME_ID == SCHEME_ID).FirstOrDefault();

                if (DateTime.Now.Date > entity.EFFECTIVE_DATE.GetDateTime().Date)
                {
                    errors.Add("已过期的入厂采样方案不能修改！");
                    return false;
                }


                if (entity == null)
                {
                    errors.Add(Resource.Disable);
                    return false;
                }
                
                entity.STATUS = intSTATUS == 0 ? 1 : 0; 
                if(entity.STATUS==1)
                {
                    //是否存在同批次的采样方案（存在则修改采样方案状态后创建新的采样方案，不存在则直接创建新的采样方案）
                    List<V_PUB_SCHEME> list = m_Rep.Context.V_PUB_SCHEME.Where(a=>a.BATCH_CODE==m_Rep.Context.V_PUB_SCHEME.Where(m => m.SCHEME_ID == SCHEME_ID).FirstOrDefault().BATCH_CODE &&a.STATUS==1).ToList();
                    
                    if (list.Count() > 0)
                    {
                        for (int i = 0; i < list.Count(); i++)
                        {
                            PUB_SCHEME item = new PUB_SCHEME();
                            item.SCHEME_ID = list[i].SCHEME_ID;
                            item.STATUS = 2;//设为废弃

                            m_Rep.Context.Set<PUB_SCHEME>().Attach(item);
                            //标识 实体对象 某些属性 已经被修改了
                            m_Rep.Context.Entry<PUB_SCHEME>(item).Property("STATUS").IsModified = true;

                            db.Configuration.ValidateOnSaveEnabled = false;
                        }
                    }
                }

                if (m_Rep.Context.SaveChanges() > 0)
                {
                    return true;
                }
                else
                {
                    errors.Add(Resource.NoDataChange);
                    return false;
                }

            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }
    }
}
